#!/usr/bin/python
import os, os.path, shutil, sys, time

from optparse import OptionParser

def parse_options():
    usage = "%prog src_dir dest_dir [options]"
    version = "%prog 0.01a"
    parser = OptionParser(usage=usage, version=version)
    parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
    parser.add_option("-s", "--sync",
                  action="store_true", dest="sync", default=False,
                  help="sync the source and destination dirs")

    (options, args) = parser.parse_args()
    if args == []:  #bail out when no argument given
        parser.print_help()
        raise SystemExit
    else:
        return (options, args)

def usage():
    print "usage: usync.py src_dir dest_dir"
    raise SystemExit

def syncdir(dir1, dir2):
    "accepts two dirs and sync the contents"
    d1 = os.path.abspath(dir1)
    d2 = os.path.abspath(dir2)

    if os.path.isdir(d1) and os.path.isdir(d2):
        for f in os.listdir(d1):
            src_file = os.path.join(d1, f)
            #directly copy file from dir1 to dir2 if it's not in dir2
            if f not in os.listdir(d2):
                print 'copying %s ......' %f
                shutil.copy2(src_file, d2) 
            #file exists in both dirs, do nothing when file sizes are equal
            elif os.path.getsize(src_file) == os.path.getsize(os.path.join(d2, f)):
                pass
            #now copy the file to dir2 when newer
            else:
                dest_file = os.path.join(d2, f)
                stime = os.path.getmtime(src_file)
                dtime = os.path.getmtime(dest_file)
                src_mtime = time.strftime('%Y-%m-%d, %H:%M', time.localtime(stime))
                dest_mtime = time.strftime('%Y-%m-%d, %H:%M', time.localtime(dtime))
                print '%s last modified: %s\n%s last modified: %s'  \
                       %(src_file, src_mtime, dest_file, dest_mtime) 
                if stime > dtime: 
                #when src file is newer:
                    answer = raw_input('copy %s to %s? [y/n]' %(src_file, dest_file))
                    if answer == 'y':
                        print 'copying %s...' %src_file 
                        shutil.copy2(src_file, dest_file)


if __name__ == '__main__':
    if len(sys.argv) != 3:
        usage()
    a1 = sys.argv[1]
    a2 = sys.argv[2]
    if os.path.isdir(a1) and os.path.isdir(a2):
        syncdir(a1, a2) 
    elif os.path.isdir(a1) and not os.path.isdir(a2):
        os.mkdir(os.path.abspath(a2))
        syncdir(a1, os.path.abspath(a2))
